import { db } from "../cloudInit.js";
const _ = db.command;
import Query from "@/utils/Query.js";
export const Calendar = new Query({
    total: 0,
    querySetting: {
        keyword: "",
    },
    search(querySetting) {
        this.querySetting = querySetting;
        this.splice(0); // 这个是 calendar 的特殊机制，向下补充数据，所以需要进行清0

        if (this.$branch === "default") {
            this.$checkout("temp");
        } else {
            this.$Query.temp.clear();
        }
        this.$to(0);
    },
    // 首页展示的那个心语签
    looking: {},
    look(_id) {
        let Looking;
        this.$Query.default.some((pages) =>
            pages.some((page) => {
                if (page._id === _id) {
                    Looking = page;
                    return true;
                }
            })
        );
        this.looking = Looking;
        return this.looking;
    },
    searchOut() {
        this.$checkout("default");
    },
    async _defaultQuery(index) {
        const Querying = db.collection("PublicXin").where({
            date: _.gt(0).and(_.lt(new Date().getTime())),
        });
        const num = 20;
        if (index === 0) {
            const { total } = await Querying.count();
            this.total = Math.ceil(total / num);
        }
        return Querying.skip(index * num)
            .orderBy("date", "desc")
            .limit(num)
            .get()
            .then(({ data }) => {
                console.log("defaultQuery", index, data);
                return [...this, ...data];
            });
    },
    async _tempSearch(index) {
        const filterList = [
            {
                isVisible: true,
            },
        ];
        const now = new Date().getTime();
        let {
            keyword = "",
            lTime = 0,
            rTime = 32536799999000,
        } = this.querySetting;

        if (keyword) {
            const gen = new db.RegExp({
                regexp: keyword,
                options: "i",
            });
            filterList.push(
                _.or([
                    {
                        description: gen,
                    },
                    { title: gen },
                    { please: gen },
                ])
            );
        }

        if (lTime < rTime) {
            rTime = rTime <= now ? rTime : now; // 超过现在的数值截断为现在
            filterList.push({ date: _.gt(lTime).and(_.lt(rTime)) });
        }
        const Querying = db.collection("PublicXin").where(_.and(filterList));

        const num = 20;
        return Querying.skip(index * num)
            .orderBy("date", "desc")
            .limit(num)
            .get()
            .then(({ data }) => {
                console.log(data);
                return [...this, ...data];
            });
    },
    async $getPage(index) {
        if (this.$branch === "default") {
            return this._defaultQuery(index);
        } else {
            return this._tempSearch(index);
        }
    },
});
